<?php
/**
 * Created by PhpStorm.
 * User: pengzhizhuang
 * Date: 17/6/5
 * Time: 上午10:40
 */

namespace App\Http\Traits;

trait AliCloudTrait
{
    //查询请求host
    protected $host = 'https://api09.aliyun.venuscn.com';
    //快递查询目录
    protected $queryPath = '/express/trace/query';
    //快递公司查询目录
    protected $typePath = '/express/type';

    /**
     * @param $number 快递单号
     * @return array
     * 快递查询
     */
    public function expressQuery($number)
    {
        $querys = http_build_query(
            array(
                'number' => $number
            )
        );
        $url = $this->host . $this->queryPath . '?' . $querys;

        $result = $this->query($url);
        if ($result['ret'] != 200) {
            $message = $this->getErrorCodeMessage($result['ret']);
            return ['status' => 0, 'message' => $message];
        }
        $result['data']['traces'] = array_reverse($result['data']['traces']);
        return ['status' => 1, 'data' => $result['data']];
    }

    /**
     * @return array
     * 获取快递公司
     */
    public function expressType()
    {
        $url = $this->host . $this->typePath;
        $result = $this->query($url);
        if ($result['ret'] != 200) {
            return ['status' => 0, 'message' => $result['msg']];
        }
        return ['status' => 1, 'data' => $result['data']];
    }

    /**
     * @param $url
     * @return mixed
     */
    private function query($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->getHeaders());
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $this->host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $result = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($result, true);

        return $result;
    }

    /**
     * @return array
     * 获取请求头信息
     */
    private function getHeaders()
    {
        $appcode = config('saas.AliCloud.APP_CODE');
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        return $headers;
    }

    /**
     * @param $errorCode
     * @return string
     * 获取错误代码提示信息
     */
    private function getErrorCodeMessage($errorCode)
    {
        $errorCodes = $this->errorCode();
        return isset($errorCodes[$errorCode]) ? $errorCodes[$errorCode] : '暂物流信息跟踪';
    }

    /**
     * @return array
     * 错误码定义
     */
    private function errorCode()
    {
        return [
            '201' => '快递单号为空',
            '202' => '快递公司为空',
            '203' => '快递公司不存在',
            '204' => '快递公司识别失败',
            '205' => '没有信息',
        ];
    }
}
